from django.shortcuts import render
from django.views import View
from django.core.paginator import Paginator, EmptyPage
from django.http import JsonResponse

from .models import SKU

from .utils import get_breadcrumb


class ListView(View):
    """分页列表接口"""

    def get(self, request, category_id):

        # 1. 提取参数
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        # 2. 校验参数

        # 3. 业务数据处理 —> 查询当前分类sku商品
        # 3.1 排序过滤出查询集
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by(ordering)  # '-create_time'

        # 3.2 分页过滤出查询集
        # page=1&page_size=5
        # (1) 实例化分页对象
        paginator = Paginator(skus, page_size)

        # (2) 获取指定页：获取第page页
        try:
            page_skus = paginator.page(page)
        except EmptyPage as e:
            return JsonResponse({'code': 400, 'errmsg': '指定页不存在'}, json_dumps_params={'ensure_ascii': False})

        # 3.3 把分页子集构建响应参数
        sku_list = [{
            'id': sku.id,
            'default_image_url': sku.default_image.url,
            'name': sku.name,
            'price': sku.price,
        }for sku in page_skus]

        total_page = paginator.num_pages  # 总页数
        breadcrumb = get_breadcrumb(category_id)

        # 4. 构建响应
        return JsonResponse({'code': 0, 'errmsg': 'ok',
                             'breadcrumb': breadcrumb,
                             'list': sku_list,
                             'count': total_page,
                             }, json_dumps_params={'ensure_ascii': False})


class HotGoodsView(View):
    """获取热销排行接口"""
    def get(self, request, category_id):

        # 1. 提取参数

        # 2. 校验参数

        # 3. 业务处理 —> 根据销量降序排列返回2个
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')

        hot_skus_list = skus[0:2]  # QuerySet 查询集支持下标切片操作
        hot_skus = [{
            'id': sku.id,
            'default_image_url': sku.default_image.url,
            'name': sku.name,
            'price': sku.price,
        } for sku in hot_skus_list]

        # 4. 构建响应
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'hot_skus': hot_skus,
                             }, json_dumps_params={'ensure_ascii': False})


# SearchView是haystack提供的一个视图类，对应的接口是: GET + /search/?q=xx
from haystack.views import SearchView


class MySearchView(SearchView):
    """搜索接口"""

    def create_response(self):
        """重写SearchView类"""
        page = self.request.GET.get('page')

        # 获取搜索结果
        context = self.get_context()  # 自动根据查询字符串参数q检索且根据分页相关参数进行分页

        # 用户搜索词：context['query']
        # 分页器对象：context['paginator']
        # 总页数：context['paginator'].num_pages
        # 默认每页数量：context['paginator'].per_page
        # 数据总量：context['paginator'].count

        # 当前页对象：context['page']
        # 搜索结果列表：context['page'].object_list
        # 搜索结果对象：SearchResult对象
        # 模型类对象：SearchResult.object属性

        # 构建响应参数
        data_list = []
        for result in context['page'].object_list:
            # result: 是一个SearchResult对象
            sku = result.object
            data_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
                'searchkey': context.get('query'),  # 用户搜索的关键词
                'page_size': context['page'].paginator.num_pages,  # 总页数
                'count': context['page'].paginator.count  # 数据总数
            })

        # 拼接参数返回，返回的是列表，safe设置为False
        return JsonResponse(data_list, safe=False)

